package edu.ycu.aladdin.web.aspect;

import edu.ycu.aladdin.web.controller.AbsController;
import edu.ycu.aladdin.web.dao.OauthDao;
import edu.ycu.aladdin.web.exception.OauthException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author <a href="mailto:wangruihuano@gmail.com">王瑞环</a>
 * @since 1.0
 */
@Aspect
@Component
@EnableAspectJAutoProxy
public class OauthAspect {

    @Autowired
    private OauthDao oauthDao;

    @Before("execution(public * edu.ycu.aladdin.web.controller.*.*(..))" +
            "&& @annotation(edu.ycu.aladdin.web.aspect.NeedLogin)")
    public void doOauth(JoinPoint point) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();

        Cookie[] cookies = request.getCookies();

        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(AbsController.COOKIE_LOGIN_KEY)) {
                    if (oauthDao.hasLogged(cookie.getValue())) {
                        return;
                    }
                }
            }
        }

        throw new OauthException("user not logged in");
    }
}